package com.kunya.common.filter;

import com.kunya.common.util.RedisPoolUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zp
 * @Description: 获取表前缀  。从redis中查询，并放入HttpServletRequest中
 * @date 2018/5/29 10:51
 */
public class RequstDataFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String serverName = httpServletRequest.getServerName();
        //如果是本地（开发测试时使用，生产上应去掉此分支）
        if (StringUtils.equals("127.0.0.1", serverName)) {
            httpServletRequest.setAttribute("currentCmsPrefix", StringUtils.EMPTY);
        } else if (StringUtils.equals("localhost", serverName)) {
            httpServletRequest.setAttribute("currentCmsPrefix", "340_");
        } else {
            String cmsUserId = RedisPoolUtil.get(serverName);
            //如果 未从redis中查到改serverName ，抛出异常
            if (StringUtils.isEmpty(cmsUserId)) {
                throw new RuntimeException("未查询到地址:" + serverName + "对应的cmsUserId");
            }
            httpServletRequest.setAttribute("currentCmsPrefix", RedisPoolUtil.get(serverName)+"_");
        }
        filterChain.doFilter(httpServletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
